import React, {useEffect, useState, useRef} from 'react'
import {GetServerSideProps, } from 'next'
import dayjs from 'dayjs'
import moment from 'moment';
import * as echarts from 'echarts';
import {getSummary} from '@request/jyReques'
import type { DatePickerProps } from 'antd'
import {DatePicker} from 'antd'

interface Props {
  summaryData: {
    data: {
      date: string;
      drhz: string;
    }[]
  }
}
const dateFormat = 'YYYY-MM-DD'

// 获取jy summary 总的数据
const getJySummary = async(time?: {sTime: string, eTime: string}) => {
  let summaryData = {}
  try {
    summaryData = await getSummary({
      url: 'http://localhost:3535/wealth/getSummary',
      data: time || { sTime: '', eTime: '', }
    }).then(data => data.json())

    // summaryData = await fetch('http://localhost:3535/wealth/getSummary', {
    //   method: 'post',
    //   // 不写默认查询
    //   body: JSON.stringify({ sTime: '', eTime: '', }),
    //   headers: { 'Content-Type': 'application/json;charset=UTF-8' }
    // }).then(data => data.json())

  } catch (error) {
    throw new Error('getJySummary error')
  }
  return summaryData
}

export default function JyIndex(props: Props) {
  const summartRef = useRef<HTMLDivElement>(null)
  const [refresh, setRefresh] = useState(0)
  const [timeDate, setTimeDate] = useState({
    sTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
    eTime: dayjs().format('YYYY-MM-DD')
  })


  const setChart = async(type?: boolean, time?: boolean) => {
    // console.log(props.summaryData)
    if(summartRef.current) {
      const myChart = echarts.init(summartRef.current)
      const option: any = {
        title: {
          text: Math.random().toString(16)
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: [], // ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: 100,
            xAxisIndex: [0, 1]
          },
        ],
        series: [
          {
            data: [], //[820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
            smooth: true,
            markPoint: {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            },
          }
        ]
      };
      const xData:string[] = []
      const seriesData: string[] = []
      if(!type) {
        props?.summaryData?.data?.forEach(item => {
          xData.push(dayjs(item.date).format('hh:mm:ss'))
          seriesData.push(item.drhz)
        })
      } else {
        if(time) { // sTime: timeDate.sTime, eTime?: string
          await getJySummary({sTime: timeDate.sTime, eTime: timeDate.eTime})
          .then((res: any) => {
            res?.data?.forEach((item: any) => {
              xData.push(dayjs(item.date).format('YYYY-MM-DD hh:mm:ss'))
              seriesData.push(item.drhz)
            });
          })
          option.xAxis.data = xData
          option.series[0].data = seriesData
          myChart.setOption(option)
          return
        }
        await getJySummary()
        .then((res: any) => {
          res?.data?.forEach((item: any) => {
            xData.push(dayjs(item.date).format('hh:mm:ss'))
            seriesData.push(item.drhz)
          });
        })
      }
      option.xAxis.data = xData
      option.series[0].data = seriesData
      myChart.setOption(option)
      window.addEventListener('resize',function(){
        myChart.resize();
      })
    }
  }
  // 找时间使用sse(server-sent events)替换setInterval
  const intervalRefresh = (time?: number, clear?: boolean) => {
    let t: any = null
    t && clearInterval(t)
    if(clear) return
    t = setInterval(() => {
      setChart(true)
    }, time || 5 * 60 * 1000);
  }
  
  useEffect(() => {
  //   fetch('http://localhost:3535/wealth/getSummary', {
  //     method: 'post',
  //     body: JSON.stringify({
  //       sTime: '', 
  //       eTime: '',
  //     }),
  //     headers: {
  //       'Content-Type': 'application/json;charset=UTF-8'
  //     }
  //   })
  //     .then(data => data.json())
  //     .then(res => {
  //       console.log(res, 'res')
  //     })

  // 创建一长连接				
    const socket = new WebSocket('ws://localhost:3536')
    socket.addEventListener('open', () => {
      // 发送数据
      socket.send(JSON.stringify({
        // 握手名称（跟后端名称保持一致）
        event : "helloSock",
        // 发送的数据
        data : {
          sTime: dayjs().format("YYYY-MM-DD 00:00:00"),
          eTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        },
      }))
    })
    socket.addEventListener('message', (e) => {
      console.log('websocket 接收到的信息', e);
    })
    socket.addEventListener('close', () => {
      console.log('webSocket 关闭');
    })
  }, [])
  useEffect(() => {
    setChart()
    intervalRefresh()
    return () => {
      intervalRefresh(0, true)
    }
  }, [])


  return (
    <div>
      JyIndex
      <button
        onClick={() => {
          setChart(true)
        }}
      >refresh</button>
      <div>
        开始日期：<DatePicker 
          defaultValue={moment(timeDate.sTime, dateFormat)} 
          format={dateFormat} 
          onChange={(data, dateString) => {
            setTimeDate(pre => ({
              ...pre,
              sTime: dateString
            }))
          }} 
        />
        结束日期：<DatePicker 
          defaultValue={moment(timeDate.eTime, dateFormat)} 
          format={dateFormat} 
          onChange={(data, dateString) => {
            setTimeDate(pre => ({
              ...pre,
              eTime: dateString
            }))
          }} 
        />
      

        <button
          onClick={() => {
            setChart(true, true)
          }}
        >开始</button>
      </div>
      <div ref={summartRef}
        style={{ width: '100vw', height: '300px', }}
      ></div>
    </div>
  )
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  const params = context.params
  let summaryData = {}
  try {
    summaryData = await getJySummary()
    // summaryData = await getSummary({
    //   url: 'http://localhost:3535/wealth/getSummary',
    //   data: { sTime: '', eTime: '', }
    // }).then(data => data.json())
    
    // summaryData = await fetch('http://localhost:3535/wealth/getSummary', {
    //   method: 'post',
    //   // 不写默认查询
    //   body: JSON.stringify({ sTime: '', eTime: '', }),
    //   headers: { 'Content-Type': 'application/json;charset=UTF-8' }
    // }).then(data => data.json())
    
  } catch (error) {
    throw new Error('getSummary ❌')
  }
  return {
    props: {
      summaryData,
    }
  }
}